package log

import (
	"errors"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo/options"
	"higame/config"
	mongodb "higame/modules/db"
)

var db = mongodb.GetInstance()

type LoginLogSchema struct {
	ID            primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
	AddTime       int64              `json:"add_time" bson:"add_time" form:"add_time"`
	Username      string             `json:"username" bson:"username"`
	LastLoginTime int64              `json:"last_login_time" bson:"last_login_time"`
	LastCheckTime int64              `json:"last_check_time" bson:"last_check_time"`
	IP            string             `json:"ip" bson:"ip"`
	Success       bool               `json:"success" bson:"success" `
	Location      string             `json:"location" bson:"location"`
	Text          string             `json:"text" bson:"text"`
	PcCode        string             `json:"pc_code" bson:"pc_code"`
	ClientID      string             `json:"client_id" bson:"client_id"`
}

func NewLoginLogSchema() *LoginLogSchema {
	return &LoginLogSchema{}
}

func ParseLoginLogSchema(data bson.M) (*LoginLogSchema, error) {
	u := NewLoginLogSchema()
	if err := db.ToStruct(data, u); err != nil {
		return nil, err
	}
	return u, nil
}

func AddOneLoginLog(log *LoginLogSchema) error {
	logI := db.InsertOne(config.Db.Collection.LogUserLogin, log)
	if !logI {
		return errors.New("添加日志失败，可能是数据连接有问题")
	}
	return nil
}

func FindManyLoginLogByUsername(username string) []bson.M {
	opts := new(options.FindOptions)
	list := db.FindMany(config.Db.Collection.LogUserLogin, bson.M{
		"username": username,
	}, opts.SetLimit(20),
		opts.SetSkip(0),
		opts.SetSort(bson.M{
			"last_login_time": -1,
		}))
	return list
}

func FindManyLoginLog(pageNum int64, filter interface{}) []bson.M {
	if pageNum > 0 {
		pageNum = pageNum - 1
	}
	opts := new(options.FindOptions)
	list := db.FindMany(config.Db.Collection.LogUserLogin, filter,
		opts.SetSkip(pageNum*20),
		opts.SetLimit(20),
		opts.SetSort(bson.M{
			"add_time": -1,
		}))
	return list
}

func CountLoginLog(filter interface{}) (int64, error) {
	return db.Count(config.Db.Collection.LogUserLogin, filter), nil
}
